// data_processor.js
(function(window) {
    function processData(file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const data = e.target.result;
            const workbook = XLSX.read(data, {type: 'binary'});
            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1});

            const headers = jsonData[0];
            const regionIndex = headers.indexOf('核算地区');
            const serviceIndex = headers.indexOf('调节服务项');
            const percentageIndex = headers.indexOf('调节服务项占比（%）');

            const services = Array.from(new Set(jsonData.slice(1).map(row => row[serviceIndex])));
            const serviceSelect = document.getElementById('serviceSelect');
            serviceSelect.innerHTML = '<option value="">请选择调节服务项</option>';
            services.forEach(service => {
                const option = document.createElement('option');
                option.value = service;
                option.textContent = service;
                serviceSelect.appendChild(option);
            });

            serviceSelect.addEventListener('change', () => {
                const selectedService = serviceSelect.value;
                if (selectedService) {
                    drawChart(selectedService);
                    drawMap(selectedService);
                } else {
                    clearCharts();
                }
            });
        };
        reader.readAsBinaryString(file);
    }

    function clearCharts() {
        if (chartInstance) chartInstance.destroy();
        if (myChart) myChart.dispose();
        document.getElementById('dataTable').getElementsByTagName('tbody')[0].innerHTML = '';
    }

    function drawChart(selectedService) {
        const filteredData = jsonData.slice(1).filter(row => row[serviceIndex] === selectedService);
        const regions = filteredData.map(row => row[regionIndex]);
        const percentages = filteredData.map(row => parseFloat(row[percentageIndex]));

        if (chartInstance) chartInstance.destroy();
        const ctx = document.getElementById('singleServiceChart').getContext('2d');
        chartInstance = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: regions,
                datasets: [{
                    label: `${selectedService}占比`,
                    data: percentages,
                    backgroundColor: [
                        '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'
                    ]
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: `单项调节各地区占比 - ${selectedService}`
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '占比 (%)'
                        }
                    }
                }
            }
        });
    }

    function drawMap(selectedService) {
        const filteredData = jsonData.slice(1).filter(row => row[serviceIndex] === selectedService);
        const transMapData = filteredData.map(item => ({
            name: formatRegionName(item[regionIndex]),
            value: parseFloat(item[percentageIndex]).toFixed(2)
        }));

        const mapContainer = document.getElementById('mapContainer');
        if (myChart) myChart.dispose();
        myChart = echarts.init(mapContainer);
        const option = {
            title: {
                text: '气候调节各省的占比地图',
                subtext: '未确认数据',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}<br/>占比: {c}%'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data:['调节服务项占比']
            },
            visualMap: {
                min: 0,
                max: 100,
                left: 'left',
                top: 'bottom',
                text: ['高', '低'], // 文本，默认为数值文本
                calculable: true,
                inRange: {
                    color: ['#e0ffff', '#006edd']
                }
            },
            series: [
                {
                    name: '调节服务项占比',
                    type: 'map',
                    mapType: 'china',
                    roam: false,
                    label: {
                        show: true
                    },
                    emphasis: {
                        show: true
                    },
                    data: transMapData
                }
            ]
        };

        myChart.setOption(option);
    }

    function formatRegionName(name) {
        const specialCases = {
            '广西壮族自治区': '广西',
            '内蒙古自治区': '内蒙古',
            '宁夏回族自治区': '宁夏',
            '新疆维吾尔自治区': '新疆',
            '西藏自治区': '西藏',
            '特别行政区': '', // 假设没有特别行政区的数据，如果有需要添加
        };

        if (specialCases[name]) {
            return specialCases[name];
        }

        const suffixesToRemove = ['省', '市'];
        for (let suffix of suffixesToRemove) {
            if (name.endsWith(suffix)) {
                return name.slice(0, -suffix.length);
            }
        }
        return name;
    }

    window.processData = processData;
    window.clearCharts = clearCharts;
    window.drawChart = drawChart;
    window.drawMap = drawMap;
    window.formatRegionName = formatRegionName;
})(window);